package chapter04.guardedSuspensionModel;

public class GuardedObject<T> {
    // 唯一id
    private int id;
    private T obj;

    public GuardedObject(){

    }

    public GuardedObject(int id){
        this.id=id;
    }



    public int getId() {
        return id;
    }

    public <T> T get(){
        synchronized (this){
            while (obj==null){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return (T) obj;
        }
    }
    public <T> T get(long timeout){
        synchronized (this){
            // 获取当前处理开始时间
            long beginTime=System.currentTimeMillis();
            // 程序运行经历的时间
            long passedTime=0;
            while (obj==null){
                // 计算这一轮应该等待的时间
                long shouldwait=timeout-passedTime;
                if (shouldwait<=0)break;
                try {
                    this.wait(shouldwait);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passedTime=System.currentTimeMillis()-beginTime;
            }
            return (T) obj;
        }
    }

    public void complete(T res){
        synchronized (this){
            this.obj=res;
            this.notifyAll();
        }
    }
}
